<?php

namespace fakis\ueditor;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\View;
use yii\widgets\InputWidget;

/**
 * 富文本编辑器
 * Class UEditor
 * @package fakis\ueditor
 *
 * @author Fakis <fakis738@qq.com>
 */
class UEditor extends InputWidget
{
    /**
     * 配置选项，参阅UEditor官网文档(定制菜单等)
     * @var array
     */
    public $clientOptions = [];

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        if (isset($this->options['id'])) {
            $this->id = $this->options['id'];
        } else {
            $this->id = $this->hasModel()
                ? Html::getInputId($this->model, $this->attribute)
                : $this->id;
        }

        $this->clientOptions = array_merge($this->getDefaultOptions(), $this->clientOptions);

        parent::init();
    }

    /**
     * 默认配置选项
     * @return array
     */
    protected function getDefaultOptions()
    {
        return [
            'serverUrl' => Url::to(['/site/ueditor']),
            'lang' => (strtolower(Yii::$app->language) == 'en-us') ? 'en' : 'zh-cn',
            'initialFrameWidth' => '100%',
            'initialFrameHeight' => '200',
            'toolbars' => [
                [
                    'fullscreen', 'source', 'undo', 'redo', '|',
                    'fontsize', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', '|',
                    'forecolor', 'backcolor', '|',
                    'justifyleft', 'justifycenter', 'justifyright', '|',
                    'lineheight', 'indent', '|',
                    'link', 'unlink', '|', 'searchreplace',
                    'removeformat', 'formatmatch', '|',
                    'insertimage'
                ],
            ]
        ];
    }

    public function run()
    {
        $this->registerClientScript();
        if ($this->hasModel()) {
            return Html::activeTextarea($this->model, $this->attribute, ['id' => $this->id]);
        } else {
            return Html::textarea($this->id, $this->value, ['id' => $this->id]);
        }
    }

    /**
     * 注册客户端脚本
     */
    protected function registerClientScript()
    {
        UEditorAsset::register($this->view);
        $clientOptions = Json::encode($this->clientOptions);

        $script = '';
        // @FIXED: 解决多次Ajax请求时，UEditor不能正常显示的问题
        if (Yii::$app->request->isAjax) {
            $script .= "UE.delEditor('" . $this->id . "');";
        }
        $script .= "UE.getEditor('" . $this->id . "', " . $clientOptions . ");";
        $this->view->registerJs($script, View::POS_READY);
    }
}
